package com.guigu.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guigu.domain.dto.AuthUserDTO;
import com.guigu.domain.entity.AuthUser;
import com.guigu.domain.enums.AuthUserStatusEnum;
import com.guigu.domain.enums.IsDeletedFlagEnum;
import com.guigu.exception.GlobalException;
import com.guigu.redis.RedisUtil;
import com.guigu.service.AuthUserDomainService;
import com.guigu.service.AuthUserService;
import com.guigu.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
@Slf4j
public class AuthUserDomainServiceImpl implements AuthUserDomainService {

    @Resource
    private AuthUserService authUserService;

    @Resource
    private EmailService emailService;

    private String salt = "chicken";
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Boolean register(AuthUserDTO authUserDTO) {
        boolean isValid = emailService.verifyCode(authUserDTO.getEmail(), authUserDTO.getCode());
        if (!isValid) {
            throw new GlobalException("验证码错误或者已过期！");
        }
        //验证成功后清除验证码缓存
        String codeKey = redisUtil.buildKey("email:code",authUserDTO.getEmail());
        String timeKey = redisUtil.buildKey("email:code",authUserDTO.getCode());
        redisUtil.del(codeKey);
        redisUtil.del(timeKey);
        //校验用户是否存在
        AuthUser authUser = new AuthUser();
        BeanUtils.copyProperties(authUserDTO, authUser);
        // 根据邮箱查询用户
        LambdaQueryWrapper<AuthUser> wrapper = new LambdaQueryWrapper<>();
        AuthUser existUser = authUserService.getOne(wrapper.eq(AuthUser::getEmail, authUser.getEmail()));
        if (ObjectUtils.isNotEmpty(existUser)) {
            throw new GlobalException("当前用户已经存在，请直接登录！");
        }
        if (StringUtils.isNotBlank(authUser.getPassword())) {
            authUser.setPassword(SaSecureUtil.md5BySalt(authUser.getPassword(), salt));
        }
        if (StringUtils.isBlank(authUser.getAvatar())) {
            authUser.setAvatar("http://117.72.10.84:9000/user/icon/微信图片_20231203153718(1).png");
        }
        if (StringUtils.isBlank(authUser.getNickName())) {
            authUser.setNickName("鸡翅粉丝");
        }
        authUser.setStatus(AuthUserStatusEnum.OPEN.getCode());
        authUser.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        return authUserService.save(authUser);
    }

    @Override
    public SaTokenInfo doLogin(String email, String password) {

        // 1. 查询用户
        LambdaQueryWrapper<AuthUser> wrapper = new LambdaQueryWrapper<>();
        AuthUser user = authUserService.getOne(wrapper.eq(AuthUser::getEmail, email));
        if (user == null) {
            throw new GlobalException("邮箱或密码错误");
        }

        // 2. 验证密码
        String md5BySalt = SaSecureUtil.md5BySalt(password, salt);
        log.info("md5BySalt:{}", md5BySalt);
        if (!user.getPassword().equals(md5BySalt)) {
            throw new GlobalException("邮箱或密码错误");
        }

        // 3. 验证账号状态
        if (user.getStatus() != 0) {
            throw new GlobalException("账号已被禁用");
        }

        // 4. Sa-Token登录
        StpUtil.login(user.getId());

        // 5. 返回Token信息
        return StpUtil.getTokenInfo();

    }

}